package com.bdqn.demo.web;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * AuthorizationInterceptor
 *
 * @author f
 * @since 2021/11/30
 */
public class AuthorizationInterceptor implements HandlerInterceptor {
    /**
     * 请求执行前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("loginUser") == null) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请先进行登陆，再进行后续操作！(Interceptor 控制)');location.href='" + request.getContextPath() + "/login.jsp';</script>");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 请求结束时执行（需要preHandle方法返回true的时候才会执行）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 视图渲染完成后才执行（需要preHandle方法返回true的时候才会执行，通常用于清理资源等工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
